#!/bin/bash

cur_dir=$(dirname "$(readlink -f "$0")")
echo "$cur_dir"

docker network create monitor_network 2>/dev/null || true

pushd "$cur_dir" || exit
for module in modules/*/; do
    if [ -d "$module" ]; then
        echo "Found directory: $module"
        echo "启动目录 $module 的 Docker Compose 服务..."
        docker compose -f "$module"/docker-compose.yml up -d
    else
        echo "目录 $module 不存在，跳过启动服务。"
    fi
done
popd || exit

# 等待 Grafana 就绪
GRAFANA_URL="http://localhost:3000/api/health"
MAX_ATTEMPTS=100
WAIT_SECONDS=3

echo "Waiting for Grafana to be ready..."
until curl -s -o /dev/null -w "%{http_code}" "$GRAFANA_URL" | grep -q "200"; do
    if [ $((attempt_num++)) -ge $MAX_ATTEMPTS ]; then
        echo "Failed to connect to Grafana after $MAX_ATTEMPTS attempts. Exiting."
        exit 1
    fi
    echo "Attempt $attempt_num of $MAX_ATTEMPTS failed. Retrying in $WAIT_SECONDS seconds..."
    sleep $WAIT_SECONDS
done
echo "Grafana is up and running!"

# 导入数据源
echo "Importing datasources and dashboards..."
pushd "$cur_dir/tools" || exit
python3 import-datasource.py
popd || exit
